import type { App, Directive, DirectiveBinding } from 'vue'
import { useUserStore } from '@/stores/user'

// 权限指令类型
interface PermissionDirectiveBinding extends DirectiveBinding {
  value: string | string[] // 权限标识或权限标识数组
}

// 检查权限
const checkPermission = (value: string | string[]): boolean => {
  const userStore = useUserStore()
  const permissions = userStore.permissions

  if (!value) return true
  if (Array.isArray(value)) {
    return value.some(permission => permissions.includes(permission))
  }
  return permissions.includes(value)
}

// 权限指令
export const permission: Directive = {
  mounted(el: HTMLElement, binding: PermissionDirectiveBinding) {
    const hasPermission = checkPermission(binding.value)
    if (!hasPermission) {
      el.parentNode?.removeChild(el)
    }
  },
  updated(el: HTMLElement, binding: PermissionDirectiveBinding) {
    const hasPermission = checkPermission(binding.value)
    if (!hasPermission && el.parentNode) {
      el.parentNode.removeChild(el)
    }
  }
}

// 注册指令
export function setupPermissionDirective(app: App) {
  app.directive('permission', permission)
}
